package com.base.common.util;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

/**
 * Image scale util class
 * @author Administrator
 *
 */
public class ImageScaleUtil {
	
	/**
	 * Resizes an image by long side
	 * @param input - source image file
	 * @param maxSize - Height and width of the longer one
	 * @param formatName - a String containg the informal name of the format
	 * @return
	 * @throws IOException
	 */
	public static boolean scaleImageByLong (File file, int maxSize, String formatName) throws IOException {
		int width 			= maxSize;
		int height 			= maxSize;
		BufferedImage bi 	= ImageIO.read(file);
		if (bi.getWidth() >= bi.getHeight()) {
			height = (int) (new Integer(bi.getHeight()).doubleValue() * width / bi.getWidth());
		} else {
			width = (int) (new Integer(bi.getWidth()).doubleValue() * height / bi.getHeight());
		}
		Image srcImage = bi.getScaledInstance(width, height, BufferedImage.TYPE_INT_RGB);
		BufferedImage resizedImage = getScaleImage(srcImage, width, height);
		return writeImage(resizedImage, formatName, file);
	}
	
	/**
	 * Resizes an image using a Graphics object backing by a BufferedImage
	 * @param srcImage - source image to scale
	 * @param width - desired width
	 * @param height - desired height
	 * @return - a new resized image
	 */
	private static BufferedImage getScaleImage (Image srcImage, int width, int height) {
		BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D g2 = resizedImage.createGraphics();
		g2.drawImage(srcImage, 0, 0, width, height, null);
		// Releases system resources 
		g2.dispose();
		return resizedImage;
	}
	
	/**
	 * Writes an image using an arbitrary ImageWriter that supports the given format to a File
	 * @param srcImage - a RenderedImage to be written
	 * @param formatName - a String containg the informal name of the format
	 * @param file - file would be written
	 * @throws IllegalArgumentException
	 * @throws IOException
	 */
	private static boolean writeImage(BufferedImage srcImage, String formatName, File file) throws IllegalArgumentException, IOException {
		return ImageIO.write(srcImage, formatName, file);
	}
	
	
}
